package main

import (
	"fmt"
	"os"
	"strings"
)

func RunAsCmd() {
	fmt.Println("\n  --- 酷软Apk签名工具(by Arvin) --- ")
	var input string = ""
	if len(os.Args) > 1 {
		input = fixName(os.Args[1])
	} else {
		fmt.Println("\n      请将要签名的apk拖到 signer.exe，或者使用 signer *.apk 来执行命令")
	}

	if len(input) > 0 {
		do(input)
	}

	fmt.Println("\n  按回车键退出")
	var si string
	fmt.Scanln(&si)
}

func do(input string) {
	fmt.Println("\n      apk：" + input)
	signOutput := getOutputName(input, "-signed.apk")
	err := DoSign(input, signOutput)
	if err != nil {
		fmt.Println("\n      签名失败:" + err.Error())
	} else {
		fmt.Println("\n      签名完成")
		defer os.Remove(signOutput)
		alignOutput := getOutputName(input, ".apk")
		err = ZipAlign(signOutput, alignOutput)

		if err != nil {
			fmt.Println("\n      Apk对齐失败:" + err.Error())
		} else {
			fmt.Println("\n      对齐成功，输出到:" + alignOutput)
		}
	}
}

func fixName(path string) string {
	path = strings.Replace(path, `\`, p, 100)
	path = strings.Replace(path, `/`, p, 100)
	return path
}

// func getSignedFileName(path string) {
// 	//-unsigned.
// }

func getOutputName(path string, suffix string) string {
	path = fixName(path)

	dir := path[0:strings.LastIndex(path, p)]
	name := path[strings.LastIndex(path, p)+1:]

	if strings.HasPrefix(name, "app-") {
		name = name[4:]
	}

	if strings.HasSuffix(name, ".apk") {
		name = name[0:(len(name) - 4)]
	}

	name = strings.Replace(name, "release", "", 1)
	name = strings.Replace(name, "unsigned", "", 1)
	name = dir + p + name + suffix
	name = strings.Replace(name, "--", "-", 100)
	name = strings.Replace(name, "-.", ".", 100)

	// if strings.HasSuffix(name, "-release-unsigned") {
	// 	name = name[0:(len(name) - 9)]
	// }

	// if strings.HasSuffix(name, "-release") {
	// 	name = name[0:(len(name) - 8)]
	// }

	return name
}
